import requestAPI from '../../utils/requestApi'
var app = getApp();
Page({
  data: {
    avatarUrl: app.globalData.avatarUrl, // 默认头像URL
    nickName: '', // 默认昵称
    genderOptions: [
      { value: 'male', text: '男', checked: false },
      { value: 'female', text: '女', checked: false }
    ],
    selectedGender: '', // 用于存储当前选中的性别
    gender: '', // 默认性别
    birthday: '', // 默认日期
    birthdayFormatted: '请选择您的生日', // 格式化后的日期显示
    phone: '', // 默认联系方式
    phoneError: '', // 联系方式错误信息
    address: {
      province: '北京市', 
      city: '北京市', 
      county: '东城区'
    },
  },
  // 选择头像
  chooseAvatar: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          avatarUrl: tempFilePaths[0]
        });
        app.globalData.avatarUrl = tempFilePaths[0];
      }
    })
  },

  // 更新昵称
  updateNickName(e) {
    const nickName = e.detail.value;
    // 使用正则表达式检查昵称是否只包含字母、汉字和数字
    const nameRegex = /^[a-zA-Z0-9\u4e00-\u9fa5]*$/; // 修改为允许空字符串
    if (!nameRegex.test(nickName)) {
      wx.showToast({
        title: '昵称不能包含特殊符号',
        icon: 'none',
        duration: 3000
      });
      // 清除非法输入
      this.setData({
        nickName: nickName.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
      });
      return;
    }
    this.setData({
      nickName: nickName
    });
    wx.setStorageSync('nickName', nickName);
  },

  // 更新性别
  updateGender(e) {
    this.setData({
      gender: e.detail.value,
      genderOptions: this.data.genderOptions.map(option => ({
        ...option,
        checked: option.value === e.detail.value
      }))
    });
  },

  // 更新生日
  updateBirthDay(e) {
    const birthday = e.detail.value;
    const today = new Date().toISOString().slice(0, 10); // 获取今天的日期，格式为 YYYY-MM-DD
    // 检查生日是否早于或等于今天
    if (birthday > today) {
      wx.showToast({
        title: '请填入正确的生日',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    const birthdayFormatted = new Date(birthday).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
    this.setData({
      birthday: birthday,
      birthdayFormatted: birthdayFormatted
    });
  },

  // 更新联系方式
  updateContact(e) {
    const phone = e.detail.value;
    const phoneError = this.validateContact(phone);
    this.setData({
      phone: phone,
      phoneError: phoneError,
    });
  },

  // 验证联系方式格式
  validateContact(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone) ? '' : '电话格式错误';
  },

  // 更新地址
  updateAddress: function(e) {
    const address = e.detail.value;
    this.setData({
      address: {
        province: address[0],
        city: address[1],
        county: address[2]
      }
    });
  },

  // 保存信息到后端
    saveInfoToBackend: function() {
      const userKey = wx.getStorageSync('userKey'); // 从本地存储获取 userKey

      if (!userKey) {
          wx.showToast({
              title: '请先登录',
              icon: 'error'
          });
          return;
      }
      // 验证电话号码格式
      const phoneError = this.validateContact(this.data.phone);
      if (phoneError) {
          wx.showToast({
              title: '请填入正确的电话号码',
              icon: 'none',
              duration: 3000
          });
          return;
      }

      // 验证生日是否早于今天
      const today = new Date().toISOString().slice(0, 10); // 获取今天的日期，格式为 YYYY-MM-DD
      if (this.data.birthday > today) {
          wx.showToast({
              title: '请填入正确的生日',
              icon: 'none',
              duration: 3000
          });
          return;
      }
      const userInfo = {
        userKey: userKey, // 添加 userKey
          avatarUrl: this.data.avatarUrl,
          nickName: this.data.nickName,
          gender: this.data.gender,
          birthday: this.data.birthday,
          phone: this.data.phone,
          address: this.data.address
      };

    // 使用封装的 API 方法
    requestAPI.post('/travel/update', userInfo).then(response => {
      if (response.code === 200) {
        wx.showToast({
          title: '信息修改成功',
          icon: 'success',
          duration: 3000
        });
        wx.setStorageSync('user', userInfo); // 保存用户信息到本地存储
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/my2/my2'
          });
        }, 1000);
      } else {
        wx.showToast({
          title: '保存用户信息失败',
          icon: 'none',
          duration: 2000
        });
        console.error('后端返回错误:', response.message);
      }
    }).catch(err => {
      console.error('Failed to save user info:', err);
      wx.showToast({
        title: '保存用户信息出错',
        icon: 'none',
        duration: 2000
      });
    });
  },


  onUnload() {
    this.resetFormIfDirty();
  },

  // 重置表单如果它被修改了且没有保存
  resetFormIfDirty() {
      this.setData({
        nickName: '',
        genderOptions: this.data.genderOptions.map(option => ({
          ...option,
          checked: false
        })),
        gender: '',
        birthday: '',
        birthdayFormatted: (new Date()).toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }),
        phone: '',
        phoneError: '',
        address: {
          province: '北京市',
          city: '北京市',
          county: '东城区'
        }
      });
  },

  // 后端获取头像和昵称
  onLoad: function(options) {
    this.fetchUserInfo();
    // 检查本地存储的用户信息并更新页面显示
    const userInfo = wx.getStorageSync('user');
    if (userInfo) {
      this.setData({
        avatarUrl: userInfo.avatarUrl,
        nickName: userInfo.nickName
      });
    }
  },

  fetchUserInfo: function () {
    const userKey = wx.getStorageSync('userKey'); // 从本地存储获取 userKey
    if (!userKey) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 2000
      });
      return;
    }
    const data = {userKey:userKey}
    const header = {'openid':userKey}
      // 调用封装的 requestAPI
      requestAPI.get('/travel/info',data,header)
        .then(response => {
          if (response.code === 200) {
            const userInfo = response.data;
    
            // 处理地址数据，确保不会显示 null 或 undefined
            let address = userInfo.address || {};
            address.province = address.province || '请选择您所在的省份';
            address.city = address.city || '城市';
            address.county = address.county || '区县';
    
            // 处理生日数据
            let birthdayFormatted = userInfo.birthday && !isNaN(Date.parse(userInfo.birthday))
              ? new Date(userInfo.birthday).toLocaleDateString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit'
                })
              : '请选择您的出生年，月，日';
    
            // 更新页面的 data
            this.setData({
              avatarUrl: userInfo.avatarUrl || this.data.avatarUrl,
              nickName: userInfo.nickName || this.data.nickName,
              genderOptions: this.data.genderOptions.map(option => ({
                ...option,
                checked: option.value === userInfo.gender
              })),
              gender: userInfo.gender || this.data.gender,
              birthday: userInfo.birthday || '',
              birthdayFormatted: birthdayFormatted,
              phone: userInfo.phone || this.data.phone,
              address: address
            });
    
            console.log('用户信息设置成功:', this.data);
          } else {
            // 后端返回的错误信息处理
            wx.showToast({
              title: response.message || '获取用户信息失败',
              icon: 'error'
            });
            console.error('后端返回错误:', response.message);
          }
        })
        .catch(error => {
          // 请求失败的处理
          if (error.statusCode === 401) {
            wx.showToast({
              title: '登录已过期，请重新登录',
              icon: 'error'
            });
            wx.redirectTo({ url: '/pages/login/login' }); // 跳转到登录页面
          } else if (error.statusCode === 500) {
            wx.showToast({
              title: '服务器错误，请稍后再试',
              icon: 'error'
            });
          } else {
            wx.showToast({
              title: '请求失败，请重试',
              icon: 'error'
            });
          }
          console.error('请求失败:', error);
        });
    }
    
});
